# encoding:utf8
"""
todo
refine by python3 await/async
"""
from mgamedev.py_lib.dhttp import DHttp as DHTTPUtil
from mgamedev.py_lib.remote import RemoteCtrl
from ccpm.glan import Lan
from ccpm.conffac import GConf
import os
from ccpm.collogger import Log
import sys
import math
# ignore https warning
from urllib3.exceptions import InsecureRequestWarning
import requests
requests.packages.urllib3.disable_warnings(category=InsecureRequestWarning)


def process_stdout(nsize, tsize):
    percent = float(nsize) / float(tsize)
    percent = round(percent*100, 2) if percent <= 100.0 else 100.0
    sys.stdout.write(
        ("Process-->>(%dbyte/%dbyte)(%0.2f%%) \r") % (int(nsize),
                                                      int(tsize), percent))
    sys.stdout.flush()
    if nsize >= tsize:
        sys.stdout.write("\n")


class NetUtil:
    @staticmethod
    def bin_chk(sign, strver="1.0.0"):
        ret = DHTTPUtil.http_post("/api/ccpm/bin_chk",
                                  {"sign": sign, "strver": strver},
                                  verify=False)
        if ret:
            if ret.get("r") == 0:
                return (True, None)
            else:
                return (False, ret["desc"])

    @staticmethod
    def plugin_exist_chk(pname):
        ret = DHTTPUtil.http_get("/api/ccpm/plugin_chk",
                                 {"name": pname}, verify=False)
        if ret:
            if ret.get("r") == 0:
                if len(ret["data"]) > 0:
                    return ret["data"]

    @staticmethod
    def tools_exist_chk(pname):
        ret = DHTTPUtil.http_get("/api/ccpm/tool_chk",
                                 {"name": pname}, verify=False)
        if ret:
            if ret.get("r") == 0 and len(ret["data"]) > 0:
                return (True, None)
            else:
                return (False, ret["desc"])

    @staticmethod
    def add_plugin_db(plugininfo):
        ret = DHTTPUtil.http_post("/api/ccpm/add_plugin",
                                  plugininfo, verify=False)

        if ret:
            if ret.get("r") == 0:
                return (True, None)
            else:
                return (False, ret["desc"])

    @staticmethod
    def dele_plugin_db(usrtype, usr, pname, pver):
        ret = DHTTPUtil.http_post("/api/ccpm/dele_plugin",
                                  {"name": pname, "ver": pver, "usr": usr, "usrtype": usrtype}, verify=False)
        if ret:
            if ret["r"] == 0:
                return (True, None)

    @staticmethod
    def add_tool_db(toolinfo):
        ret = DHTTPUtil.http_post("/api/ccpm/add_tool",
                                  toolinfo, verify=False)
        if ret["r"] == 0:
            if ret["data"] == 0:
                return True
        return False

    @staticmethod
    def sftp_upload(pwd, pzipf, remotehost, remotepath, **kwads):
        if not pzipf:
            Log().error(Lan.g("FILE_NOT_FIND"))
            sys.exit(1)
        ctl = RemoteCtrl(remotehost, usr="root", pwd=pwd)
        relf = pzipf.split(os.sep)[-1]

        Log().info("uploading the plugin--->>>%s", pzipf)
        ret = ctl.commit_file(pzipf,
                              "%s/%s" % (remotepath, relf), process_stdout)
        return ret

    @staticmethod
    def oss2_upload(bucket, remotepath, pzipf, **kwads):

        ret = bucket.put_object_from_file(
            remotepath, pzipf, {}, process_stdout)

        return ret.status == 200

    @staticmethod
    def unzip_remotezip(pzipf, **kwad):
        host = GConf().get("host")
        pwd = GConf().get("pwd")
        ctl = RemoteCtrl(host, usr="root", pwd=pwd)
        tarpath = pzipf.split(".zip")[0]
        Log().info("unzip the remote zip file-->%s  to <%s>", pzipf, tarpath)
        ret = ctl.ssh_command(
            "unzip -o {pzipf} -d {tarpath} ".format(pzipf=pzipf, tarpath=tarpath))

    @staticmethod
    def ftp_download(url, localp, **kwads):
        Log().info("downloading the plugin from<%s> to <%s>", url, localp)
        dfile = DHTTPUtil.download_file(
            url, localp, process_cb=process_stdout)

    @staticmethod
    def oss2_download(bucket, url, localp, **kwads):
        Log().info("downloading the plugin from<%s> to <%s>", url, localp)
        # 下载OSS文件到本地文件。如果指定的本地文件存在会覆盖，不存在则新建。
        ret = bucket.get_object_to_file(
            url, localp, progress_callback=process_stdout)

        if int(ret.status) == 200:
            return localp

    @staticmethod
    def get_plugin_pageinfo(url):
        ret = DHTTPUtil.http_get("/api/ccpm/get_pageinfo", verify=False)
        if ret["r"] == 0:
            return (True, ret["data"])
        else:
            return (False, "def error")
